package com.payService.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.payService.Client.EduCourse;
import com.payService.entity.TOrder;
import com.payService.service.ITOrderService;
import com.payService.service.ITPayLogService;
import com.payService.utils.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 支付日志表 前端控制器
 * </p>
 *
 * @author Mr.Tang
 * @since 2022-05-31
 */
@RestController
@RequestMapping("/tpaylog")
@CrossOrigin
public class TPayLogController {

    @Autowired
    private ITOrderService itOrderService;

    @Autowired
    private ITPayLogService payLogService;

    @Autowired
    private EduCourse eduCourse;


    //生成微信支付二维码接口
    //参数是订单号
    @GetMapping("createNative/{orderNo}")
    public R createNative(@PathVariable("orderNo") String orderNo) {
        //返回信息，包含二维码地址，还有其他需要的信息
        Map map = payLogService.createNatvie(orderNo);
        System.out.println("****返回二维码map集合:"+map);
        return R.ok().data("data",map);
    }



    /**
     *
     * 获取订单支付状态
     *
     * */
    @GetMapping("getPayStatus/{orderId}")
    public R getPayStatus(@PathVariable("orderId") String orderId){
        Map<String,String> map = payLogService.getPayStatus(orderId);
        System.out.println(map);
        if(map == null){
            return  R.error().msg("支付出错了！");
        }
        if (map.get("trade_state").equals("SUCCESS")){
            //查询返回结果了支付成功了
            payLogService.handleSuccessPay( map);
            //该课程购买次数加1
            QueryWrapper queryWrapper = new QueryWrapper();
            queryWrapper.eq("order_no",orderId);
            TOrder order = itOrderService.getOne(queryWrapper);
            eduCourse.paySuccessCount(order.getCourseId());
            return R.ok().msg("支付成功！");
        }
        return R.ok().code(25000).msg("支付中.....");
    }


}
